//
//  HomeTableViewController.swift
//  weibo
//
//  Created by 张宏芝 on 15/8/31.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeTableViewController: BaseTableViewController {

    
//    微博列表数据模型
   private lazy var statusListViewModel = StatusListViewModel()
//    动画提供者
    private lazy var photoBrowserAnimator = PhotoBrowserAnimator()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !UserAccountViewModel.sharedUserAccount.userLogon{
            visitorView?.setupInfo(nil, message: "关注一些人，回这里看看有什么惊喜")
            return
        }
        
//        注册通知
        /**
          1.通知'名'
          2.对象,监听'发送通知'的对象,如果是nil,监听的时所有发送该通知的对象
          3.队列,调度block的队列,如果是nil,在主线程调度block执行
          4.block:接受到通知执行的方法
         注意:通知中得block,只要使用self,就会有循环引用的陷阱
        */
        
        NSNotificationCenter.defaultCenter().addObserverForName(HZStatusPictureViewSelectedPhotoNotification, object: nil, queue: nil) { [weak self](notification) -> Void in
            
            guard let urls = notification.userInfo![HZStatusPictureViewSelectedPhotoURLsKey] as? [NSURL] else{
                return
            }
            guard let indexPath = notification.userInfo![HZStatusPictureViewSelectedPhotoIndexPathKey] as? NSIndexPath else{
                return
            }
            guard let picView = notification.object as? StatusPictureView else {
                return
            }
            
            let vc = PhotoBrowserViewController(urls:urls,indexPath:indexPath)
            // 指定动画的提供者,从一个界面跳转到另一个界面
            vc.transitioningDelegate = self?.photoBrowserAnimator
            // 指定modal的展现样式是自定义的
            vc.modalPresentationStyle = UIModalPresentationStyle.Custom
            // 计算位置
            let fromRect = picView.screenRect(indexPath)
            let toRect = picView.fullScreenRect(indexPath)
            
            self?.photoBrowserAnimator.prepareAnimator(picView,fromRect:fromRect, toRect: toRect, url: urls[indexPath.item])
            self?.presentViewController(vc, animated: true, completion: nil)
        }
        
        prepareTableView()
        loadData()
    }
    
//    通知销毁
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    private func prepareTableView(){
//        注册cell
//    注册可重用 cell
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: HMStatusForwardCellID)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: HMStatusNormalCellID)
        tableView.estimatedRowHeight = 300
        
        //        如果不使用自动计算行高的:UITableViewAutomaticDimension,不设置底部的约束
        tableView.rowHeight = UITableViewAutomaticDimension
        //        取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
//        准备下拉刷新控件,控件的高度是60
        refreshControl = HZRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
//        下拉刷新(将上拉的视图添加到表格的footerView上)
        self.tableView.tableFooterView = pullView
    }
    
    func loadData(){
//        beginRefreshing:只会播放刷新的动画,不会加载数据
        refreshControl?.beginRefreshing()
        
        statusListViewModel.loadStatuses(isPullupRefresh: pullView.isAnimating()).subscribeNext({ (result) -> Void in
            let count = (result as! NSNumber).integerValue
            self.showPulldownTips(count)
            
            }, error: { (error) -> Void in
//                关闭刷新控件
                self.endloadData()
                printLog(error)
                SVProgressHUD.showInfoWithStatus("网络不给力,重新加载")
            }) { //   没有参数:可以直接省略() -> Void in
//                关闭刷新控件
                self.endloadData()
                self.tableView.reloadData()
        }
    }
    
    private func showPulldownTips(count:Int){
        printLog(count)
        let title = count == 0 ? "没有新微博" : "刷新到\(count)条微博"
        let label = UILabel(title: title, color: UIColor.whiteColor(), fontSize: 18)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        let heigth:CGFloat = 44
        let rect = CGRect(x: 0, y: -2 * heigth, width: UIScreen.mainScreen().bounds.width, height: heigth)
        label.frame = rect
        pulldownTipLabel.text = title
        pulldownTipLabel.frame = rect
        navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        UIView.animateWithDuration(1.2, animations: {
            
            self.pulldownTipLabel.frame = CGRectOffset(rect, 0, 3 * heigth)
            
            }) { (_) -> Void in
                UIView.animateWithDuration(1.2) { self.pulldownTipLabel.frame = rect }
        }
    }
//    停止刷新数据
    private func endloadData(){
        self.refreshControl?.endRefreshing()
        self.pullView.stopAnimating()
    }
    
/// MARK:懒加载
//    下拉提示标签
    private lazy var pulldownTipLabel:UILabel = {
        let label = UILabel(title: nil, color: UIColor.whiteColor(), fontSize: 18)
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        return label
    }()
//    下拉刷新的控件
    private lazy var pullView :UIActivityIndicatorView = {
       let indecator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indecator.backgroundColor = UIColor.darkGrayColor()
        return indecator
    }()
}
extension HomeTableViewController {
    
   override func tableView(tableView:UITableView, numberOfRowsInSection section:Int) ->Int{
        return statusListViewModel.statuses.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let viewModel = statusListViewModel.statuses[indexPath.row] as! StatusViewModel
        let cell = tableView.dequeueReusableCellWithIdentifier(viewModel.cellID, forIndexPath: indexPath) as! StatusCell
        cell.statusViewModel = viewModel
        
//        判断是不是最后一行,如果是开启上拉刷新的动画
        if(indexPath.row == statusListViewModel.statuses.count - 1) && !pullView.isAnimating(){
            print("上拉刷新")
            pullView.startAnimating()
            loadData()
        }
        
        // 5. 设置 cell 的代理
        cell.cellDelegate = self
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
//       0.获得模型
        let viewModel = statusListViewModel.statuses[indexPath.row] as! StatusViewModel
//        1.判断视图模型的行高,如果不为0就进行行高的缓存
        if viewModel.rowHeigth > 0{
            printLog("返回缓存行高")
            return viewModel.rowHeigth
        }
        
//       2.获得cell,不能使用indexPath的方法,否则会出现死循环
        let cell = tableView.dequeueReusableCellWithIdentifier(viewModel.cellID) as! StatusCell
        
//       3.记录行高
        viewModel.rowHeigth = cell.rowHeight(viewModel)
        return viewModel.rowHeigth
    }
}

extension HomeTableViewController: StatusCellDelegate {
    func statusCellDidClickURL(url: NSURL) {
        let vc = HomeWebViewController()
        
        vc.url = url
        vc.hidesBottomBarWhenPushed = true
        
        navigationController?.pushViewController(vc, animated: true)
    }
}




























